package com.tianqi.familymap.utils

import android.content.Context
import android.util.Log
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.orhanobut.logger.Logger
import com.tianqi.familymap.entry.MyApp
import com.tianqi.familymap.http.RetrofitHelper
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

class OkHttpUtils(private var str:String) {
    private val TAG = "OkHttpUtils"
    private val DEFAULT_READ_TIMEOUT_MILLIS:Long = 15 * 1000
    private val DEFAULT_WRITE_TIMEOUT_MILLIS:Long = 20 * 1000
    private val DEFAULT_CONNECT_TIMEOUT_MILLIS:Long = 20 * 1000
    private val HTTP_RESPONSE_DISK_CACHE_MAX_SIZE:Long = 10 * 1024 * 1024
    @Volatile
    private var okHttpClient:OkHttpClient? = null

    /**
     * 获取log拦截器，单例模式，仅获取一次，共APP全局使用
     */
    init{
        //设置HttpLoggingInterceptor
        val interceptor = HttpLoggingInterceptor { message ->
            try {
                Log.i(TAG, message)
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e(TAG, message)
            }
        }
        //包含header、body数据
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        //setlevel用来设置日志打印的级别，共包括了四个级别：NONE,BASIC,HEADER,BODY
        //BASEIC:请求/响应行
        //HEADER:请求/响应行 + 头
        //BODY:请求/响应行 + 头 + 体
        okHttpClient = OkHttpClient.Builder()
            .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
            //FaceBook 网络调试器，可在Chrome调试网络请求，查看SharePreferences,数据库等
            .addNetworkInterceptor(StethoInterceptor())
            .addInterceptor(interceptor)
            .addInterceptor(MyInterceptor(str))
            //持久化Cookie，OKHttp管理Cookie
            //用户登录时保存的cookie，在下次需要用到该用户的cookie放在请求头里
            .build()
    }
    companion object : SingletonHolder<OkHttpUtils, String>(::OkHttpUtils)

//    companion object{
//        private var instance: OkHttpUtils? = null
//            get() {
//                if (field == null){
//                    field = OkHttpUtils()
//                }
//                return field
//            }
//        fun get(): OkHttpUtils{
//            return instance!!
//        }
//    }

    /**
     * 获取OkHttpClient
     *
     * @return
     */
    fun getOkHttpClient():OkHttpClient{
        return okHttpClient!!
    }
}